﻿using System;
using System.Windows;
using MvvmBase.Converters;
using jinek.Prometheus.Views.Converters;

namespace MvvmBase.Behavior
{
    public class CallDataContextsMethodAction : System.Windows.Interactivity.TriggerAction<FrameworkElement>
    {
        public string MethodName { get; set; }
        public string ArgumentsPathForParameter { get; set; }

        protected override void Invoke(object eventArgs)
        {
            if (string.IsNullOrEmpty(this.MethodName))
            {
                return;
            }

            var dataContext = AssociatedObject.DataContext;
            if (dataContext == null)
            {
                return;
            }
            var type = dataContext.GetType();
            var methodInfo = type.GetMethod(this.MethodName);
            if (methodInfo == null)
            {
                throw new MemberAccessException(
                    string.Format("Method {0} not found. Ensure that it has public instance signature", this.MethodName));
            }

            if (!string.IsNullOrEmpty(ArgumentsPathForParameter))
            {
                object valueToPath;

                if(ArgumentsPathForParameter=="this") ArgumentsPathForParameter = string.Empty;

                valueToPath = TypeExpanderExtension.GetProperty(eventArgs, ArgumentsPathForParameter);
                //nothing to return
                methodInfo.Invoke(dataContext, new[] {valueToPath});
            }
            else
            {
                methodInfo.Invoke(dataContext, new object[0]);
            }
        }
    }
}